package com.gitee.fitness.service;

import com.alibaba.fastjson.JSONObject;
import com.gitee.fitness.config.RabbitMqConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
@RabbitListener(queues = RabbitMqConfig.QUEUE_NAME)
@Slf4j
public class RabbitMqReceiver {
    //方法：接收消息

    @RabbitHandler
    public void process(Object message, Channel channel) throws Exception{
        Message message1 = (Message) message;
        String messageStr = new String(message1.getBody(), StandardCharsets.UTF_8);
        JSONObject jsonObject;
        try {
            jsonObject = JSONObject.parseObject(messageStr);
            log.info("接收到的消息-->{}", jsonObject);
            int i=1/0;
            channel.basicAck(message1.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception ignored) {
            log.warn("异常:{}",ignored.getMessage());
            channel.basicNack(message1.getMessageProperties().getDeliveryTag(), false,false);
//            if (retryCount >= 3) {
//                log.info("超过重试次数，不重新进入队列");
//                channel.basicReject(message1.getMessageProperties().getDeliveryTag(), false);
//            }else {
//                channel.basicNack(message1.getMessageProperties().getDeliveryTag(), false, true);
//            }
        }

    }
}
